<template>
  <view class="payment" v-if="!Data.loading">
    <view class="pay-number">
      <price-point style="text-align: center;" :price="Data.totalFee" :size="48"></price-point>
      <view class="time">
        <view class="text">
          剩余时间
        </view>
        <view class="num">
          {{ hou }}
        </view>
        <view class="colon">
          :
        </view>
        <view class="num">
          {{ min }}
        </view>
        <view class="colon">
          :
        </view>
        <view class="num">
          {{ sec }}
        </view>
      </view>
    </view>
    <radio-group class="ways">
      <label class="item">
        <view class="pay-name">
          <view class="img">
            <image src="/static/images/wxpay.png" />
          </view>
          <view class="name">微信支付</view>
        </view>
        <radio :checked="true" />
      </label>
    </radio-group>

    <view class="sure-pay" @tap="surePay">
      确定付款
    </view>
  </view>
</template>

<script setup>
  import {
    reactive
  } from 'vue'
  import Wechat from '../../utils/wechat.js'

  const wxs = number()

  const Data = reactive({
    isWechat: false, // 是否为微信环境
    payType: PayType.ALIPAY_H5,
    PayTypeConstant: PayType,
    appType: uni.getStorageSync('cloudAppType'),
    totalFee: 0,
    totalScore: 0,

    orderIds: '', // 订单id
    dvyType: 1, // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送

    timer: '', // 定时器名称
    endTime: '', // 订单过期时间
    countDown: false, // 倒计时变量
    hou: '', // 时
    min: '', // 分
    sec: '', // 秒
    loading: true
  })
  const {
    totalFee,
    hou,
    min,
    sec,
    loading
  } = toRefs(Data)

  onLoad((options) => {
    // #ifdef H5
    Data.isWechat = Wechat.isWechat()
    // #endif
    // #ifdef APP-PLUS
    Data.isWechat = false
    Data.payType = PayType.ALIPAY_APP
    // #endif
    // #ifdef MP-WEIXIN
    Data.isWechat = false
    Data.payType = PayType.WECHATPAY
    // #endif
    if (options.orderIds) {
      Data.orderIds = options.orderIds
    }
    if (options.isPurePoints) {
      Data.isPurePoints = options.orderIds
    }
  })

  onShow(() => {
    getOrderPaymentInfo()
  })

  onUnload(() => {
    clearTimeout(Data.timer)
  })

  onHide(() => {
    clearTimeout(Data.timer)
  })

  /**
   * 获取订单支付信息
   */
  const getOrderPaymentInfo = () => {
    const params = {
      url: '/mall4cloud_order/a/order/order_pay_info',
      method: 'GET',
      data: {
        orderIds: Data.orderIds
      }
    }
    http.request(params).then((res) => {
      Data.totalFee = res.totalFee
      Data.totalScore = res.totalScore
      Data.endTime = res.endTime
      Data.loading = false
      // 生成倒计时
      getCountDown()
    })
  }

  /**
   * 生成支付倒计时
   */
  const getCountDown = () => {
    const nowTime = new Date().getTime() // 现在时间（时间戳）
    const endTime = new Date(Data.endTime.replace(/-/g, '/')).getTime() // 结束时间（时间戳）
    const time = (endTime - nowTime) / 1000 // 距离结束的毫秒数
    // 获取时、分、秒
    let hou = parseInt(time % (60 * 60 * 24) / 3600)
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
    hou = timeFormin(hou)
    min = timeFormin(min)
    sec = timeFormin(sec)
    Data.hou = timeFormat(hou)
    Data.min = timeFormat(min)
    Data.sec = timeFormat(sec)
    // 每1000ms刷新一次
    if (time > 0) {
      Data.countDown = true
      Data.timer = setTimeout(getCountDown, 1000)
    } else {
      Data.countDown = false
      uni.redirectTo({
        url: `/pages/payment-result/payment-result?sts=0&orderIds=${Data.orderIds}`
      })
      // this.$Router.push('/pages/orderList/orderList')
    }
  }

  // 小于10的格式化函数（2变成02）
  const timeFormat = (num) => {
    return num < 10 ? '0' + num : num
  }

  // 小于0的格式化函数（不会出现负数）
  const timeFormin = (num) => {
    return num < 0 ? 0 : num
  }

  // 确认支付
  const surePay = () => {
    uni.showModal({
      title: '提示',
      content: '确定是否付款',
      showCancel: true, // 是否显示取消按钮
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          orderPay()
        } else if (res.cancel) {
          uni.showToast({
            title: '取消支付',
            icon: 'none',
            duration: 1500
          })
        }
      }
    })
    // uni.navigateTo({
    //   url: '/pages/payment-result/payment-result'
    // })
  }
  const orderPay = () => {
    const orderIdList = Data.orderIds.split(',')
    const params = {
      url: '/mall4cloud_payment/pay/order',
      method: 'POST',
      data: {
        orderIds: orderIdList
      }
    }
    http.request(params).then((res) => {
      handlePayResult(res)
    }).catch((res) => {
      if (res.msg == '用户openId不存在,请先登记用户信息') {
        console.log('用户openId不存在,请先登记用户信息')
        setWXOpenIdAndPay()
      } else {
        uni.showToast({
          title: res.msg,
          duration: 2000,
          icon: 'none'
        })
      }
    })
  }
  const setWXOpenIdAndPay = () => {
    // openId是发起支付的必要数据，如果没有openId，那就先登记openId
    uni.login({
      complete(res) {
        http.request({
          url: '/mall4cloud_user/a/user/ma/update_wx_open_id?code=' + res.code,
          method: 'GET',
        }).then(() => {
          console.log('用户openId登记完毕，继续尝试支付')
          const orderIdList = Data.orderIds.split(',')
          const params = {
            url: '/mall4cloud_payment/pay/order',
            method: 'POST',
            data: {
              orderIds: orderIdList
            }
          }
          http.request(params).then((res) => {
            handlePayResult(res)
          })
        })
      }
    })
  }
  const handlePayResult = (res) => {
    console.log(res)
    if (res.body) {
      let miniPayRequest = JSON.parse(res.body)
      // wx.requestPayment({
      //   timeStamp: res.miniPayRequest.timeStamp,
      //   nonceStr: res.miniPayRequest.nonceStr,
      //   package: res.miniPayRequest.package,
      //   signType: "RSA",
      //   paySign: res.miniPayRequest.paySign,
      //   success: function (res) {
      //     // 支付成功处理逻辑
      //     // 跳转成功页面
      //     uni.redirectTo({
      //       url: `/pages/payment-result/payment-result?sts=1&orderIds=${Data.orderIds}`
      //     })
      //   },
      //   fail: function (res) {
      //     // 支付失败处理逻辑
      //   }
      // })
      let appPayRequest = ''
      appPayRequest = encodeURIComponent(JSON.stringify({
        sign: miniPayRequest.sign,
        prepayid: miniPayRequest.prepayid
      }))
      wx.navigateToMiniProgram({
        appId: miniPayRequest.miniuser,
        path: `${miniPayRequest.minipath}?appPayRequest=${appPayRequest}`,
        success() {
          uni.redirectTo({
            url: `/pages/payment-result/payment-result?sts=1&orderIds=${Data.orderIds}`
          })
        },
        fail() {
          uni.showToast({
            title: '打开支持小程序失败',
            duration: 2000,
            icon: 'none'
          })
        }
      })
    } else if (res == '支付金额为0，无需支付') {
      // 支付成功处理逻辑
      // 跳转成功页面
      uni.redirectTo({
        url: `/pages/payment-result/payment-result?sts=1&orderIds=${Data.orderIds}`
      })
    } else {
      uni.showToast({
        title: res,
        icon: 'none'
      })
    }
  }
</script>

<style lang="scss" scoped>
  @use "payment";
</style>
